<template>
	<navigatorComp
		:title="isEdit ? '墓地基本信息' : '创建墓地'"
		bgcColor="#121512"
		fontColor="#fff"
	></navigatorComp>

	<view class="display_flex createHall_tab">
		<up-tabs
			:current="currentTab"
			lineWidth="48rpx"
			lineHeight="6rpx"
			:activeStyle="{ color: '#fff' }"
			:inactiveStyle="{ color: '#666666' }"
			itemStyle="font-weight: 500;font-size: 36rpx;margin-bottom:25rpx;width:250rpx;"
			lineColor="#F3E0BB"
			:list="tablist"
			@click="clickTab"
		></up-tabs>
	</view>
	<scroll-view :style="{ height: height + 'px' }" scroll-y="true">
		<view class="createHall_inputBox" style="margin-bottom: 24rpx">
			<view class="createHall_title" v-if="currentTab === 1">逝者1</view>
			<u-form label-width="100" :label-style="obj" :model="formData" ref="uForm">
				<u-form-item label="逝者姓名:" prop="name" required>
					<u-input
						v-model.trim="formData.firstName"
						maxlength="6"
						border="none"
						placeholder="请输入逝者姓名"
						clearable
						inputAlign="right"
						fontSize="28rpx"
						color="#fff"
					/>
				</u-form-item>
				<u-form-item label="逝者性别:" prop="firstGender" required>
					<up-radio-group
						activeColor="#7cd172"
						v-model="formData.firstGender"
						size="30rpx"
						iconColor="#121512"
					>
						<up-radio
							label="男"
							:labelSize="14"
							:name="1"
							labelColor="#ECECEC"
						></up-radio>
						<view style="width: 48rpx; height: 30rpx"></view>
						<up-radio
							label="女"
							:labelSize="14"
							:name="2"
							labelColor="#ECECEC"
						></up-radio>
					</up-radio-group>
				</u-form-item>
				<u-form-item label="出生日期:" prop="birth" required>
					<view
						@click="openChooseDay(1)"
						:class="['placeHolder', formData.firstBirthTime && 'value']"
					>
						{{
							formData.firstBirthTime
								? formData.firstBirthTime.isLunar
									? '农历 ' + toChineseCanlender2(formData.firstBirthTime.date)
									: '公历 ' + formatTimestamp4(formData.firstBirthTime.date)
								: '请选择出生日期'
						}}
					</view>
					<image
						class="arrow_right"
						src="http://112.124.50.179:8888/imgs/home/arrow_right.png"
						mode=""
						@click="openChooseDay(1)"
					></image>
				</u-form-item>
				<u-form-item label="逝世日期:" prop="deadTime" required>
					<view
						@click="openChooseDay(2)"
						:class="['placeHolder', formData.firstDeathTime && 'value']"
					>
						{{
							formData.firstDeathTime
								? formData.firstDeathTime.isLunar
									? '农历 ' + toChineseCanlender2(formData.firstDeathTime.date)
									: '公历 ' + formatTimestamp4(formData.firstDeathTime.date)
								: '请选择逝世日期'
						}}
					</view>
					<image
						class="arrow_right"
						src="http://112.124.50.179:8888/imgs/home/arrow_right.png"
						mode=""
						@click="openChooseDay(2)"
					></image>
				</u-form-item>
			</u-form>
		</view>

		<view class="createHall_inputBox" v-if="currentTab == 1">
			<view class="createHall_title">逝者2</view>
			<u-form label-width="100" :label-style="obj" :model="formData" ref="uForm">
				<u-form-item label="逝者姓名:" prop="name" required>
					<u-input
						v-model="formData.secondName"
						border="none"
						placeholder="请输入逝者姓名"
						clearable
						inputAlign="right"
						fontSize="28rpx"
						color="#fff"
					/>
				</u-form-item>
				<u-form-item label="逝者性别:" prop="sex" required>
					<up-radio-group
						activeColor="#7cd172"
						iconColor="#121512"
						v-model="formData.secondGender"
						size="30rpx"
					>
						<up-radio
							label="男"
							:labelSize="14"
							:name="1"
							labelColor="#ECECEC"
						></up-radio>
						<view style="width: 48rpx; height: 30rpx"></view>
						<up-radio
							label="女"
							:labelSize="14"
							:name="2"
							labelColor="#ECECEC"
						></up-radio>
					</up-radio-group>
				</u-form-item>
				<u-form-item label="出生日期:" prop="birth" required>
					<view
						@click="openChooseDay(3)"
						:class="['placeHolder', formData.secondBirthTime && 'value']"
					>
						{{
							formData.secondBirthTime
								? formData.secondBirthTime.isLunar
									? '农历 ' + toChineseCanlender2(formData.secondBirthTime.date)
									: '公历 ' + formatTimestamp4(formData.secondBirthTime.date)
								: '请选择出生日期'
						}}
					</view>
					<image
						class="arrow_right"
						src="http://112.124.50.179:8888/imgs/home/arrow_right.png"
						mode=""
						@click="openChooseDay(3)"
					></image>
				</u-form-item>
				<u-form-item label="逝世日期:" prop="deadTime" required>
					<view
						@click="openChooseDay(4)"
						:class="['placeHolder', formData.secondDeathTime && 'value']"
					>
						{{
							formData.secondDeathTime
								? formData.secondDeathTime.isLunar
									? '农历 ' + toChineseCanlender2(formData.secondDeathTime.date)
									: '公历 ' + formatTimestamp4(formData.secondDeathTime.date)
								: '请选择逝世日期'
						}}
					</view>
					<image
						class="arrow_right"
						src="http://112.124.50.179:8888/imgs/home/arrow_right.png"
						mode=""
						@click="openChooseDay(4)"
					></image>
				</u-form-item>

				<!-- <u-form-item
					label="逝者证明(仅自己可见):"
					prop="profile"
					labelPosition="top"
					labelWidth="300rpx"
					required
				>
					<view class="uploadBox">
						<view
							v-if="!formData.secondDeathCertificate"
							class="uploadBox_add"
							@click="uploadProfile(2)"
						>
							<up-icon name="plus" size="40" color="#999999"></up-icon>
						</view>
						<image
							v-else
							class="uploadBox_add_img"
							:src="formData.secondDeathCertificate"
							mode=""
						></image>

						<view class="uploadBox_agreement">
							<up-checkbox
								:customStyle="{ marginBottom: '8px' }"
								label=""
								:name="1"
								shape="circle"
								labelSize="24rpx"
								labelColor="#999999"
								activeColor="#7cd172"
								usedAlone
								size="30rpx"
								v-model:checked="formData.isAgreement2"
							></up-checkbox>
							<view class="uploadBox_agreement_text">
								<text style="font-weight: 500">无法提供</text>
								逝者证明,我承诺内容真实有效,我愿意承担法律责任
							</view>
						</view>
					</view>
				</u-form-item> -->
			</u-form>
		</view>
		<view class="display_flex createHall_inputBox_tip">
			<image :src="imgUrl + 'imgs/home/temple_att.png'" mode="aspectFill"></image>
			平台声明：您在使用本平台服务时所提交的所有信息必须真实有效。您需对此承担完全的法律责任，感谢您的配合与支持。
		</view>
		<view class="safeArea"></view>
	</scroll-view>

	<!-- 日期选择插件 -->
	<datePicker
		ref="datePickerRef"
		@submit="confirmDate($event)"
		title="选择日期"
		:menus="dateMenus"
		:defaultDate="defaultDate"
		:defaultLunar="defaultLunar"
		:startDate="startDate"
	/>

	<view class="footerBtn_cemetery" @click="createObituary">
		<view class="footerBox_cemetery"></view>
		<view class="footerFixed_cemetery">
			<view :class="['footer_btn_cemetery', btnDisable && 'footer_btn_cemetery_inActive']">
				<!-- 新增 -->
				<view v-if="!isEdit" style="width: 40rpx; height: 40rpx; margin-right: 10rpx">
					<!-- 免费创建 -->
					<image
						v-if="!coinNumber"
						style="width: 40rpx; height: 40rpx"
						:src="imgUrl + 'imgs/home/add_memory.png'"
						mode=""
					></image>
					<!-- 付费创建，余额充足 -->
					<image
						v-if="coinNumber"
						style="width: 40rpx; height: 40rpx"
						:src="imgUrl + 'imgs/home/coin.png'"
						mode=""
					></image>
				</view>
				{{
					isEdit
						? '保存'
						: coinNumber
						? coinNumber > myYbNumber
							? '福币不足，去充值'
							: `${coinNumber}福币创建墓地`
						: '免费创建墓地'
				}}
			</view>
		</view>
		<view class="footerText" v-if="!isEdit">创建成功之后,可去设置页面补充完善更多信息</view>
	</view>
</template>

<script setup>
import { onReady, onLoad, onShow } from '@dcloudio/uni-app';
import { imgUrl } from '@/external/utils/imgUrl';
import { onMounted, ref, reactive, nextTick, getCurrentInstance, computed } from 'vue';
import navigatorComp from '/components/navigator/index.vue';
import datePicker from '/uni_modules/nj-birthday-picker/components/nj-birthday-picker/nj-birthday-picker.vue';
import { timeFormat } from '@/node_modules/uview-plus';
import _ from 'lodash';
import CommonApi from '@/API/commenApi';
import HomeApi from '@/API/home/index.js';
import store from '@/store/index.js';
import { toChineseCanlender2, formatTimestamp4 } from '@/utils/time.js';

const homeApi = new HomeApi();
const commonApi = new CommonApi();

//日期选择器
const defaultDate = ref(new Date()); //默认日期
const defaultLunar = ref(false); //是否是农历
const startDate = ref(new Date(1901, 0, 1)); //开始时间
const dateType = ref(1); //日期选择器对应的日期类型，1是开始时间1
const dateMenus = ref(['solar', 'lunar']); //日期选择器，公历和公历tab
const datePickerRef = ref(''); //日期选择组件

const coinNumber = ref(0); //福币支付数量
const myYbNumber = ref(0); //我的福币余额

onLoad((options) => {
	isEdit.value = options.isEdit == 1 ? true : false;

	//如果是编辑页，需要请求详情接口
	if (isEdit.value) {
		query();
	}

	//是否需要支付福币
	getIsPay();
});
onReady(() => {
	uni.createSelectorQuery()
		.select('.createHall_tab')
		.boundingClientRect((res) => {
			height.value =
				uni.getSystemInfoSync().screenHeight -
				getApp().globalData.bottom -
				res.height -
				uni.upx2px(200) -
				getApp().globalData.navHeight;
		})
		.exec();
});

onShow(() => {
	// 获取个人的福币信息
	getUserInfo();
});
const obj = reactive({
	'font-size': '28rpx',
	color: '#FFFFFF'
});
const $chooseImg = getCurrentInstance().appContext.config.globalProperties.$chooseImg;
const tablist = reactive([
	{
		name: '单人'
	},
	{
		name: '双人'
	}
]);
const currentTab = ref(0); //默认为创建的墓地，0
const formData = ref({
	firstName: '',
	firstGender: '',
	firstBirthTime: '',
	firstDeathTime: '',
	secondName: '',
	secondGender: '1',
	secondBirthTime: '',
	secondDeathTime: '',
	createType: '1',
	memorialId: '0'
});
const height = ref(0);
const isEdit = ref(false);
const length = ref(0);

/**
 * 打开日期选择器
 */
const openChooseDay = (type) => {
	dateType.value = type;
	datePickerRef.value.show();
};

/**
 * 日期选择器，点击确定
 */
const confirmDate = (e) => {
	console.log(e);
	let date = {
		isLunar: e.isLunar,
		date: e.date
	};
	if (dateType.value === 1) {
		//出生日期1
		if (new Date(e.date) > new Date(formData.value.firstDeathTime.date)) {
			uni.showToast({
				icon: 'none',
				title: '出生日期不能大于逝世日期'
			});
			formData.value.firstBirthTime = '';
		} else {
			formData.value.firstBirthTime = date;
		}
	} else if (dateType.value === 2) {
		//逝世日期1
		if (new Date(e.date) < new Date(formData.value.firstBirthTime.date)) {
			uni.showToast({
				icon: 'none',
				title: '逝世日期不能小于出生日期'
			});
			formData.value.firstDeathTime = '';
		} else {
			formData.value.firstDeathTime = date;
		}
	} else if (dateType.value === 3) {
		//出生日期2
		if (new Date(e.date) > new Date(formData.value.secondDeathTime.date)) {
			uni.showToast({
				icon: 'none',
				title: '出生日期不能大于逝世日期'
			});
			formData.value.secondBirthTime = '';
		} else {
			formData.value.secondBirthTime = date;
		}
	} else if (dateType.value === 4) {
		//逝世日期2
		if (new Date(e.date) < new Date(formData.value.secondBirthTime.date)) {
			uni.showToast({
				icon: 'none',
				title: '逝世日期不能小于出生日期'
			});
			formData.value.secondDeathTime = '';
		} else {
			formData.value.secondDeathTime = date;
		}
	}
};

/**
 * 是否免费创建
 */
const getIsPay = async () => {
	let res = await commonApi.getConsumeList({ pos: 1 });
	if (res.code === 0) {
		coinNumber.value = res.data.items[0].number;
	}
};

/**
 * 获取个人信息
 */
const getUserInfo = async () => {
	await store.dispatch('setUserInfo');
	myYbNumber.value = store.state.userInfo.userInfo.ybCoinNumber;
};

/**
 * 切换tab
 */
const clickTab = (item) => {
	currentTab.value = item.index;
	// if (!JSON.parse(uni.getStorageSync('cemeteryItem')).memorialId) {
	// 	formData.value = {
	// 		firstName: '',
	// 		firstGender: '',
	// 		firstBirthTime: '',
	// 		firstDeathTime: '',
	// 		secondName: '',
	// 		secondGender: '1',
	// 		secondBirthTime: '',
	// 		secondDeathTime: '',
	// 		createType: '1',
	// 		memorialId: '0'
	// 	};
	// } else {
	// 	query();
	// }
};
const query = () => {
	homeApi
		.getMemorialInfoApi({
			memorialId: JSON.parse(uni.getStorageSync('cemeteryItem')).memorialId
		})
		.then((res) => {
			//判断是双人还是单人
			currentTab.value = res.data.peopleList.length - 1;
			//赋值
			formData.value.firstName = res.data.peopleList[0].name;
			formData.value.firstGender = res.data.peopleList[0].gender;
			formData.value.firstBirthTime = {
				date: res.data.peopleList[0].birthTime,
				isLunar: res.data.peopleList[0].calendar == 2 ? true : false
			};
			formData.value.firstDeathTime = {
				date: res.data.peopleList[0].deathTime,
				isLunar: res.data.peopleList[0].calendar == 2 ? true : false
			};
			//双人
			if (res.data.peopleList.length === 2) {
				formData.value.secondName = res.data.peopleList[1].name || '';
				formData.value.secondGender = res.data.peopleList[1].gender || '';
				formData.value.secondBirthTime = {
					date: res.data.peopleList[1].birthTime,
					isLunar: res.data.peopleList[1].calendar == 2 ? true : false
				};
				formData.value.secondDeathTime = {
					date: res.data.peopleList[1].deathTime,
					isLunar: res.data.peopleList[1].calendar == 2 ? true : false
				};
			}
			formData.value.createType = '2';
			formData.value.memorialId = JSON.parse(uni.getStorageSync('cemeteryItem')).memorialId;
		});
};

const formatter = (type, value) => {
	if (type === 'year') {
		return `${value}年`;
	}
	if (type === 'month') {
		return `${value}月`;
	}
	if (type === 'day') {
		return `${value}日`;
	}
	return value;
};

/**
 * 按钮禁用
 */
const btnDisable = computed(() => {
	if (
		!formData.value.firstName ||
		!formData.value.firstGender ||
		!formData.value.firstBirthTime ||
		!formData.value.firstDeathTime
	) {
		return true;
	} else {
		if (currentTab.value === 1) {
			//双人
			if (
				!formData.value.secondName ||
				!formData.value.secondGender ||
				!formData.value.secondBirthTime ||
				!formData.value.secondDeathTime
			) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
});

const validate = () => {
	if (!formData.value.firstImageUrl) {
		uni.showToast({
			icon: 'none',
			title: '请上传遗像'
		});
		return false;
	} else if (!formData.value.firstName) {
		uni.showToast({
			icon: 'none',
			title: '请输入逝者姓名'
		});
		return false;
	} else if (!formData.value.firstGender) {
		uni.showToast({
			icon: 'none',
			title: '请选择逝者性别'
		});
		return false;
	} else if (!formData.value.firstBirthTime) {
		uni.showToast({
			icon: 'none',
			title: '请选择出生日期'
		});
		return false;
	} else if (!formData.value.firstDeathTime) {
		uni.showToast({
			icon: 'none',
			title: '请选择逝世日期'
		});
		return false;
	} else if (!formData.value.isAgreement && !formData.value.firstDeathCertificate) {
		uni.showToast({
			icon: 'none',
			title: '请上传逝者证明'
		});
		return false;
	}

	if (currentTab.value === 1) {
		//双人管
		if (!formData.value.secondImageUrl) {
			uni.showToast({
				icon: 'none',
				title: '请上传遗像'
			});
			return false;
		} else if (!formData.value.secondName) {
			uni.showToast({
				icon: 'none',
				title: '请输入逝者姓名'
			});
			return false;
		} else if (!formData.value.secondGender) {
			uni.showToast({
				icon: 'none',
				title: '请选择逝者性别'
			});
			return false;
		} else if (!formData.value.secondBirthTime) {
			uni.showToast({
				icon: 'none',
				title: '请选择出生日期'
			});
			return false;
		} else if (!formData.value.secondDeathTime) {
			uni.showToast({
				icon: 'none',
				title: '请选择逝世日期'
			});
			return false;
		} else if (!formData.value.isAgreement2 && !formData.value.secondDeathCertificate) {
			uni.showToast({
				icon: 'none',
				title: '请上传逝者证明'
			});
			return false;
		}
	}

	return true;
};
//  FirstCalendarType     int64 `form:"firstCalendar,options=1|2"` //逝者日期类型
//         SecondCalendarType    int64 `form:"secondCalendar,optional"` //逝者日期类型
const createObituary = _.throttle(function (item) {
	//福币余额不足，去充值
	if (myYbNumber.value < coinNumber.value) {
		goUrl('/subPages/mine/cloudCoin/recharge');
		return;
	}

	//置灰，点击无效
	if (btnDisable.value) {
		return;
	}

	let params = {
		...formData.value,
		firstCalendar: formData.value.firstBirthTime.isLunar ? 2 : 1,
		firstBirthTime: formData.value.firstBirthTime.date,
		firstDeathTime: formData.value.firstDeathTime.date,
		secondCalendar: formData.value.secondBirthTime?.isLunar ? 2 : 1,
		secondBirthTime: formData.value.secondBirthTime.date,
		secondDeathTime: formData.value.secondDeathTime.date
	};

	homeApi
		.createMemorialApi(params)
		.then((res) => {
			uni.showToast({
				title: isEdit.value ? '编辑成功！' : '创建成功'
			});
			setTimeout(() => {
				uni.navigateBack({
					delta: 1
				});
			}, 1000);
		})
		.catch(() => {});
}, 3000);

const goUrl = (url) => {
	uni.navigateTo({
		url: url
	});
};
</script>

<style lang="scss">
page {
	background-color: #121512;
	/* #ifdef H5 */
	padding-top: 0;
	/* #endif */
	overflow: hidden;
	box-sizing: border-box;
}

.createHall_tab {
	margin: 32rpx 0 24rpx;
}

.createHall_inputBox {
	margin: 0 32rpx 0 32rpx;
	background: linear-gradient(225deg, rgba(41, 43, 42, 0.4) 0%, rgba(138, 145, 142, 0.4) 100%);
	border-radius: 8rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 40rpx 32rpx 0 40rpx;
	box-sizing: border-box;

	.createHall_title {
		width: 100%;
		font-weight: 500;
		font-size: 28rpx;
		color: #ffffff;
		line-height: 40rpx;
		margin-bottom: 32rpx;
	}

	.createHall_avater {
		width: 132rpx;
		height: 176rpx;
		margin-bottom: 24rpx;
		border-radius: 8rpx;
	}

	.uploadText {
		font-weight: 400;
		font-size: 24rpx;
		color: #ffffff;
		line-height: 28rpx;
		margin-bottom: 48rpx;
	}

	.createHall_input {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	::v-deep .u-form {
		width: 100%;
		padding-left: 10rpx;
		box-sizing: border-box;
	}

	::v-deep .input-placeholder {
		font-weight: 400;
		font-size: 28rpx;
		color: #999999 !important;
		line-height: 33rpx;
		text-align: right;
	}

	::v-deep .uni-input-input {
		font-weight: 400;
		font-size: 28rpx;
		color: #ffffff;
		line-height: 33rpx;
		text-align: right;
	}

	::v-deep .u-form-item__body__right__content__slot {
		display: flex !important;
		align-items: center !important;
		justify-content: flex-end !important;
	}

	::v-deep .u-form-item__body {
		padding: 0 !important;
		margin-bottom: 32rpx !important;
	}

	::v-deep .u-radio-group--row {
		justify-content: flex-end !important;
	}

	.placeHolder {
		font-weight: 400;
		font-size: 28rpx;
		color: #999999;
		line-height: 33rpx;
		text-align: right;
	}

	.value {
		color: #ffffff;
	}

	.arrow_right {
		width: 40rpx;
		height: 40rpx;
	}
}

.createHall_inputBox_tip {
	font-weight: 400;
	font-size: 24rpx;
	color: #999999;
	line-height: 36rpx;
	justify-content: flex-start;
	margin: 24rpx 50rpx 0 32rpx;
	text-align: justify;

	image {
		width: 40rpx;
		height: 40rpx;
		margin:0 5rpx;
	}
}

.uploadBox {
	width: 100%;
	margin-top: 24rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;

	.uploadBox_add {
		width: 124rpx;
		height: 124rpx;
		background-color: #666666;
		border-radius: 2rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.uploadBox_add_img {
		width: 124rpx;
		height: 124rpx;
		border-radius: 2rpx;
	}

	.uploadBox_agreement {
		display: flex;
		align-items: flex-start;

		.uploadBox_agreement_text {
			width: 272rpx;
			height: 114rpx;
			font-size: 24rpx;
			color: #ececec;
			line-height: 38rpx;
			text-align: justify;
		}
	}
}

.footerBtn_cemetery {
	width: 100%;
	z-index: 1;

	.footerBox_cemetery {
		width: 100%;
		height: calc(env(safe-area-inset-bottom) + 180rpx);
	}

	.footerFixed_cemetery {
		position: fixed;
		bottom: 40rpx;
		left: 0;
		width: 100%;
		/* #ifdef H5 */
		height: 120rpx;
		/* #endif */
		/* #ifndef H5 */
		height: calc(env(safe-area-inset-bottom) + 120rpx);
		/* #endif */
		display: flex;
		align-items: center;
		flex-direction: column;
		padding: 16rpx 0;
		box-sizing: border-box;
	}

	.footer_btn_cemetery {
		width: 400rpx;
		height: 88rpx;
		box-sizing: border-box;
		background: #f3e0bb;
		border-radius: 48rpx;
		font-size: 32rpx;
		color: #524630;
		font-weight: 500;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.footer_btn_cemetery_inActive {
		opacity: 0.5;
	}

	.footerText {
		position: fixed;
		bottom: 10rpx;
		left: 50%;
		transform: translateX(-50%);
		font-weight: 400;
		font-size: 24rpx;
		line-height: 70rpx;
		color: #999999;
		white-space: nowrap;
		/* #ifdef H5 */
		height: 50rpx;
		/* #endif */
		/* #ifndef H5 */
		height: calc(env(safe-area-inset-bottom) + 50rpx);
		/* #endif */
	}
}
</style>
